<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form'
import type { VxeTableGridOptions } from '#/adapter/vxe-table'
import { computed, h, ref, onBeforeMount } from 'vue'
import { Page, useVbenModal, prompt } from '@vben/common-ui'
import { Button, message } from 'ant-design-vue'
import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { getMMeetIndex, exportMMeet, getSupplyOptions } from '#/api/mMeet'
import { getWarehouseList, getSupplyList } from '#/api/common'
import dayjs from 'dayjs'
import { useDebounceFn } from '@vueuse/core'

interface RowType {
  [key: string]: any
}

const field_data = ref<any>([])
const list = ref<any>([])
const footerData = ref<any>([])
const keyword = ref<any>({
  supplyCode: '',
})

// 表单配置
const formOptions: VbenFormProps = {
  wrapperClass: 'grid-cols-5',
  schema: [
    {
      component: 'ApiSelect',
      fieldName: 'd*SupplyCode',
      label: '供应商',
      operator: 'IN',
      componentProps: () => ({
        api: fetchFactoryOptions,
        filterOption: false,
        onSearch: useDebounceFn((value: string) => {
          keyword.value.supplyCode = value
        }, 300),
        params: { keyword: keyword.value.supplyCode || undefined },
        allowClear: true,
        showSearch: true,
        immediate: false,
        alwaysLoad: true,
        mode: 'multiple',
        visibleEvent: 'onFocus',
        onDropdownVisibleChange: (open: boolean) => {
          console.log('visible', open)
          if (open) keyword.value.supplyCode = ''
        },
      }),
    },
    {
      component: 'RangePicker',
      fieldName: 'a*record_date',
      defaultValue: [dayjs().subtract(1, 'year').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
      label: '单据日期',
      operator: 'RANGE',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
    },
    {
      component: 'RangePicker',
      fieldName: 'yf_months',
      label: '月份',
      operator: '123',
      render: 'customRender',
      componentProps: {
        picker: 'month',
        valueFormat: 'YYYY-MM',
      },
    },
  ],
  showCollapseButton: true,
  collapsed: true,
  submitOnChange: false,
  submitOnEnter: true,
}

// 表格配置
const gridOptions: VxeTableGridOptions<RowType> = {
  border: true,
  showFooter: true,
  treeConfig: {
    transform: true,
    rowField: 'id',
    parentField: 'parent_id', // 改为正确的父节点字段
    lazy: true,
    hasChild: 'hasChild',
    loadMethod({ row }) {
      // 异步加载子节点
      return fetchChildListApi(row)
    },
  },
  columns: [],
  height: '770px',
  size: 'mini',
  keepSource: true,
  pagerConfig: {
    enabled: false,
  },
  rowConfig: {
    useKey: true,
    keyField: 'id',
    //  isCurrent: true,
    isHover: true,
  },
  scrollX: {
    gt: 20,
  },
  scrollY: {
    gt: 20,
  },

  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: async ({ page }, formValues) => {
        const search = await gridApi.formApi.getFiltersValues(formValues)
        var data = await getMMeetIndex({
          page: page.currentPage,
          limit: page.pageSize,
          search,
        })
        columnsInit(data)
        // 确保第一级数据包含hasChild属性
        const formattedData = (data.data || []).map((item: any) => ({
          ...item,
          hasChild: true, // 假设所有顶级节点都可以展开
        }))
        footerInit(formattedData)
        return formattedData
      },
    },
  },
  footerRowClassName: ({ row }) => {
    return 'text-red-500'
  },
  footerMethod: ({ columns, data }) => {
    return [footerData.value]
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    resizable: true,
    search: true,
    zoom: true,
  },
  id: 'm_meet_list',
  customConfig: {
    storage: true,
  },
}

// 初始化表格
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents: {},
})

const footerInit = (res: any) => {
  // 计算各字段的合计值
  if (res.length > 0) {
    // 获取所有动态月份字段
    const monthFields = field_data.value || []

    // 创建合计对象
    const totalRow: any = {
      supply_code: '合计',
      in_no: '',
    }

    // 初始化每个月份字段的合计值为0
    monthFields.forEach((field: string) => {
      totalRow[field] = 0
    })

    // 累加每个月份字段的值
    res.forEach((item: any) => {
      monthFields.forEach((field: string) => {
        if (item[field] !== undefined && item[field] !== null) {
          totalRow[field] += parseFloat(item[field]) || 0
        }
      })
    })

    // 赋值给footerData
    footerData.value = totalRow
  } else {
    // 如果没有数据，清空footerData
    footerData.value = { supply_code: '合计' }
  }
}
// 初始化表格列
const columnsInit = (res: any) => {
  field_data.value = res.all_month
  list.value = res.data

  if (list.value && list.value.length > 0) {
    const dynamicColumns = field_data.value.map((col: any, index: number) => {
      return {
        field: col,
        title: col,
        width: 80,
        hasChild: true,
      }
    })
    const columns = [
      {
        field: 'supply_code',
        title: '供应商编码',
        width: 120,
        treeNode: true,
      },
      {
        field: 'in_no',
        title: '入库单号',
        width: 120,
      },
      {
        field: '',
        title: '（按月）应付数据',
        children: [...dynamicColumns],
      },
    ]
    gridApi.grid.loadColumn(columns)
  }
}
// 模拟后台
const fetchChildListApi = async (parentRow: any) => {
  const search = await gridApi.formApi.getFiltersValues()
  const data = await getMMeetIndex({
    page: 1,
    limit: 10,
    supply_code: parentRow.supply_code || '0',
    search,
    type: 2,
  })

  return data || []
}

// 导出功能
const handleExport = async () => {
  const hide = message.loading('正在导出...', 0)
  try {
    const search = await gridApi.formApi.getFiltersValues()
    await exportMMeet({
      search,
      is_exp: true,
    })
  } catch (e) {
    message.error('导出失败')
  } finally {
    hide()
  }
}
// 获取供应商选项
const fetchFactoryOptions = async ({ keyword = '' }: Record<string, any>) => {
  const { list } = await getSupplyList({
    quick_search: keyword,
    page: 1,
    limit: 30,
    initKey: 'id',
    initValue: '',
    select: true,
  })
  return list.map((item: any) => ({
    label: item.SupplyNa,
    value: item.SupplyCode,
  }))
}

const fetchData = async () => {
  gridApi.reload()
}
</script>

<template>
  <Page>
    <Grid>
      <template #toolbar-actions>
        <Button type="ghost" class="mr-2 bg-[#24b916] text-white hover:opacity-75" @click="handleExport">导出数据</Button>
      </template>
    </Grid>
  </Page>
</template>
